package com.cloud.form.api.translator;

import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aspose.words.Bookmark;
import com.aspose.words.BookmarkCollection;
import com.aspose.words.Cell;
import com.aspose.words.CellCollection;
import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.Node;
import com.aspose.words.NodeType;
import com.aspose.words.Row;
import com.aspose.words.RowCollection;
import com.aspose.words.Table;
import com.cloud.form.api.entity.FormAssemblyInst;

public class TableTranslator {
	private static final Logger logger = LoggerFactory.getLogger(TableTranslator.class);

	public static void translator(Document doc, String bookmark, String value, FormAssemblyInst inst) {
		JSONArray arrayVal = JSON.parseArray(value);
		if (arrayVal.size() > 0) {
			BookmarkCollection bookMarks = doc.getRange().getBookmarks();
			@SuppressWarnings("unchecked")
			Iterator<Bookmark> it = bookMarks.iterator();
			DocumentBuilder builder = new DocumentBuilder(doc);
			while (it.hasNext()) {
				Bookmark mark = it.next();
				if (mark.getName().equals(bookmark)) {
					try {
						builder.moveToBookmark(mark.getName());
						Node node = builder.getCurrentNode();
						while (node.getNodeType() != NodeType.TABLE && null != node) {
							node = node.getParentNode();
						}
						Table table = (Table) node;
						RowCollection rows = table.getRows();
						for (int i = 0; i < arrayVal.size(); i++) {
							JSONObject obj = arrayVal.getJSONObject(i);
							Row row = rows.get(i + 1);
							if (null == row) {
								row = (Row) rows.get(i).deepClone(true);
								rows.insert(i + 2, row);
							}
							CellCollection cells = row.getCells();
							Iterator cellIt =cells.iterator();
							while(cellIt.hasNext()){
								Cell c = (Cell) cellIt.next();
								BookmarkCollection cellBookmarks = c.getRange().getBookmarks();
								Bookmark bm = cellBookmarks.get(0);
								bm.setText(obj.getString(bm.getName()));
							}
						}
					} catch (Exception e) {
						logger.error("表格控件渲染失败", e);
					}
				}
			}
		}
	}

}
